﻿using SalesSys.DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using hlib.Code;
//using SalesSys.Comm.Utility;

namespace SalesSys.BLL
{
    public class DepotCommodityBLL : BaseBLL<DepotCommodity>
    {

        /// <summary>
        /// 根据仓库和货品编号查询仓库货品
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public DepotCommodity GetDepotCommodity(Guid depotId, Guid commodityId)
        {
            DepotCommodity depotCommodity = Rep.Entities.FirstOrDefault(p => p.Provider.Id == depotId && p.Commodity.Id == commodityId);
            return depotCommodity;
        }

        public KeyValuePair<int, DepotCommodity[]> GetDepotCommodityList(Guid? depotId, string name = null,
            string keyStr = null, int page = 1, int rows = 10)
        {
            var query = Rep.Entities;
            if (depotId != null)
            {
                query = query.Where(p => p.ProviderId == depotId);
            }
            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.Where(p => p.Commodity.Name.Contains(name));
            }
            query = query.WhereIf(p => p.Commodity.Supplier.Name.Contains(keyStr), !string.IsNullOrWhiteSpace(keyStr));
            var count = query.Count();
            var val = query.OrderByDescending(p => p.UpdateTime).ThenBy(p => p.Commodity.Brand).
                ThenBy(p => p.Commodity.Name)
                .ThenBy(p => p.Commodity.Standard)
                .ThenBy(p => p.Commodity.Format)
                .Paging(page, rows).DistinctBy(p => p.CommodityId)
                .ToArray();
            return new KeyValuePair<int, DepotCommodity[]>(count, val);
        }

    }
}
